﻿using CardMonitor.Model;
using CardMonitor.Utils;
using CardMonitor.ViewModel;
using CardMonitor.Windows;
using DirectShowLib;
using DotNetSpeech;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WPFMediaKit.DirectShow.Controls;

namespace CardMonitor.Pages
{
    /// <summary>
    /// BuyCard.xaml 的交互逻辑
    /// </summary>
    public partial class BuyCard : Page
    {
        BillModel billModel = null;
        private PortControlHelper pchSend;
        private PortControlHelper portWrite;
        private String curInputTag = "mobile";
        //private SolidColorBrush activeBrush = new SolidColorBrush(Color.FromRgb(186, 234, 255));
        MainWindow mainWindow = null;
        SynchronizationContext _syncContext = null;
        ImageBrush imageBrush;
        SpVoice speech = new SpVoice();
        System.Drawing.Image image;
        IntPtr icdev = IntPtr.Zero;
        int st;
        IndexViewModel viewModel;
        KeyBoardWindow inputWindow = null;
        InputWindow carInputWindow = null;
        private Action<int, String> callbackAction;
        private int cameraIndex = 0;  //记录当前选择的摄像头的索引值
        private string imgTempPath = "";

        public BuyCard()
        {
            InitializeComponent();
            billModel = new BillModel();
            viewModel = new IndexViewModel();
            viewModel.index = 0;
            _syncContext = SynchronizationContext.Current;

            this.DataContext = billModel;
            for (int i = 0; i < 7; i++)
            {
                viewModel.waiPiWeighArray.Add("");
                viewModel.waiMaoWeighArray.Add("");
            }
            mainWindow = (MainWindow)Window.GetWindow(this);
            callbackAction += CallBackExcute;

            this.Loaded += MMPage_Loaded;

        }
        public void MMPage_Loaded(object sender, RoutedEventArgs e)
        {
            this.KeyDown += MMPage_KeyDown;
            if (!"销售业务".Equals(billModel.Type))
            {

            }


            CameraConn();

        }
        private void CameraConn()
        {
            //if (player != null && player.IsRunning)
            //{
            //    player.SignalToStop();
            //    player.WaitForStop();

            //}
            //FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            //if (videoDevices.Count > 0)
            //{
            //    var videoDevice = new VideoCaptureDevice(videoDevices[0].MonikerString);
            //    videoDevice.VideoResolution = videoDevice.VideoCapabilities[0];  //设置分辨率
            //    player.VideoSource = videoDevice; //设置源
            //   player.Start(); //启动
            //}

            if (MultimediaUtil.VideoInputNames.Length > 0)//视频输入设备数量
            {
                cameraIndex = 0;// 设置摄像头的索引为 0，代表选择第一个可用的视频输入设备。
                vce.VideoCaptureSource = MultimediaUtil.VideoInputNames[cameraIndex]; // 设置摄像头的索引为 0，代表选择第一个可用的视频输入设备。
             
                try
                {
                      
                    vce.Play();  // 尝试播放视频源。
                   // vce.Close();
                    if (vce.ActualWidth > 0 && vce.ActualHeight > 0)
                    {
                        //MessageBox.Show("摄像头已成功打开并显示视频流！");
                    }
                    else
                    {
                       // MessageBox.Show("摄像头未打开");
                        vce.Close();

                      
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message+"1");
                }
            }
            else
            {
            }
        }

        public BuyCard(BillModel billModel, MainWindow _win)
        {
            InitializeComponent();
            _syncContext = SynchronizationContext.Current;

            this.billModel = billModel;
            viewModel = new IndexViewModel();
            viewModel.index = 0;
            this.DataContext = billModel;

            if (billModel.OuterSkinWeight != null)
            {
                char[] charArray = billModel.OuterSkinWeight.ToCharArray();
                int len =billModel.OuterSkinWeight.Length;


                if (len < 7)
                {
                    for (int i = 0; i < billModel.OuterSkinWeight.Length; i++)
                    {
                        viewModel.waiPiWeighArray.Add(charArray[i].ToString());
                    }

                    for (int i = 0; i < 7-len; i++) {
                        viewModel.waiPiWeighArray.Add("");
                    }

                }
                else {
                    for (int i = 0; i < 7; i++)
                    {
                        viewModel.waiPiWeighArray.Add(charArray[i].ToString());
                    }
                }
            }
            else
            {
                for (int i = 0; i < 7; i++)
                {
                    viewModel.waiPiWeighArray.Add("");
                }
            }
            if (billModel.OuterGrossWeight != null)
            {
                char[] charArray = billModel.OuterGrossWeight.ToCharArray();

                int len = billModel.OuterGrossWeight.Length;

                if (len < 7)
                {
                    for (int i = 0; i < billModel.OuterGrossWeight.Length; i++)
                    {
                        viewModel.waiMaoWeighArray.Add(charArray[i].ToString());
                    }

                    for (int i = 0; i < 7 - len; i++)
                    {
                        viewModel.waiMaoWeighArray.Add("");
                    }

                }
                else
                {
                    for (int i = 0; i < 7; i++)
                    {
                        viewModel.waiMaoWeighArray.Add(charArray[i].ToString());
                    }
                }


            }
            else
            {
                for (int i = 0; i < 7; i++)
                {
                    viewModel.waiMaoWeighArray.Add("");
                }
            }
            if (billModel.TrailerNumber != null)
            {
                char[] charArray = billModel.TrailerNumber.ToCharArray();

                int len = billModel.TrailerNumber.Length;


                if (len < 7)
                {
                    for (int i = 0; i < billModel.TrailerNumber.Length; i++)
                    {
                        viewModel.carNoArray02.Add(charArray[i].ToString());
                    }

                    for (int i = 0; i < 7 - len; i++)
                    {
                        viewModel.carNoArray02.Add("");
                    }

                }
                else
                {
                    for (int i = 0; i < 7; i++)
                    {
                        viewModel.carNoArray02.Add(charArray[i].ToString());
                    }
                }

            }
            else
            {
                for (int i = 0; i < 7; i++)
                {
                    viewModel.carNoArray02.Add("");
                }
            }

            if (billModel.OuterWeightImg != null)
            {
                LoadImage(billModel.OuterWeightImg);
            }

            this.Loaded += new RoutedEventHandler(Sign_Loaded);

            this.DataContext = billModel;
            callbackAction += CallBackExcute;

            mainWindow = _win;
            this.Loaded += MMPage_Loaded;
        }
        public void setPersonImage(ImageBrush image)
        {
            this.imageBrush = image;
         //   this.cardImagePanel.Background = image;


            //System.Drawing.Image bmp = image; // 自己初始化的有效的 image
            //System.IO.MemoryStream ms = new System.IO.MemoryStream();
            //System.Windows.Media.Imaging.BitmapImage bi = new System.Windows.Media.Imaging.BitmapImage();
            //bi.BeginInit();
            //bi.StreamSource = new MemoryStream(ms.ToArray()); // 不要直接使用 ms
            //bi.EndInit();
            //cardImage.Source = bi; // done!
            //ms.Close();

            //System.Drawing.Image bmp = image; // 自己初始化的有效的 image
            //System.Windows.Media.Imaging.BitmapSource bi =
            //System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
            //bmp.GetHbitmap(),
            //IntPtr.Zero,
            //Int32Rect.Empty,
            //BitmapSizeOptions.FromEmptyOptions());
            // 上面以 bmp 格式为例的,其他格式自处理
            //this.cardImage.Source = bi; // Done!
            //this.cardImage.Source= BitmapFrame.Create(image, BitmapCreateOptions.None, BitmapCacheOption.Default);;
        }
        private void Sign_Loaded(object sender, RoutedEventArgs e)
        {
            //MessageBox.Show(cardInfo.CardNo);
            //System.IO.MemoryStream objMSPhoto = new System.IO.MemoryStream(cardInfo.ArrPhotoByte, 0, cardInfo.ArrPhotoByte.Length);

            //ImageBrush imageBrush = new ImageBrush();
            //ImageSourceConverter imageSourceConverter = new ImageSourceConverter();
            //imageBrush.ImageSource = (ImageSource)imageSourceConverter.ConvertFrom(objMSPhoto);

            //this.cardImagePanel.Background = imageBrush;

            //MessageBox.Show(billModel.CarNo);
        }
        private void goIndex(object sender, RoutedEventArgs e)//首页
        {
            //if (player != null && player.IsRunning)
            //{
            //    player.SignalToStop();
            //    player.WaitForStop();

            //}
            vce.Close();
            Index index = new Index(mainWindow);
            mainWindow.BreakSpeak();
            
            
            //if (inputWindow != null)
            //{
            //    inputWindow.Hide();

            //}
            //if (carInputWindow != null)
            //{
            //    carInputWindow.Hide();
            //}

            // 确保隐藏其他窗口
            inputWindow?.Hide();
            carInputWindow?.Hide();
            //CardDeviceUtil.ReceiveCard();
            NavigationService.GetNavigationService(this).Navigate(index);

            //NavigationService.GetNavigationService(this).Navigate(new Uri("/Pages/Index.xaml", UriKind.Relative));
        }

        private void showMessage(String message)
        {
            InfoWindow infoWindow = new InfoWindow(message);
            infoWindow.Owner = mainWindow;
            infoWindow.ShowDialog();
        }
        private Nullable<double> getZhong(String type)
        {
            try
            {
                if ("waiPi".Equals(type))
                {
                    return Double.Parse(billModel.OuterSkinWeight);
                }
                else if ("waiMao".Equals(type))
                {
                    return Double.Parse(billModel.OuterGrossWeight);
                }else if ("waiJing".Equals(type))
                {
                    return double.Parse(billModel.OuterNetWeight);
                }
                else
                {
                    return 0.0;
                }
            }
            catch
            {
                return 0.0;
            }
        }

        private void doMakeCard(object sender, RoutedEventArgs e)//采购报道
        {
            string WorkMode = (string)App.getConfig().WorkMode;
            if (WorkMode.Equals("0"))
            {
                doMakeCardIC();//IC卡
            }
            else
            {
                doMakeCardID();//身份证
            }
        }
        private void doMakeCardID()//采购身份证报道
        {

            mainWindow.BreakSpeak();


            if (billModel.OuterGrossWeight == null || billModel.OuterGrossWeight == "")
            {
                showMessage("请按照原发磅单填写原发净重");
                return;
            }
            double OuterGrossWeight = double.Parse(billModel.OuterGrossWeight);
            double MaxWeigh = double.Parse(App.getConfig().MaxWeigh);

            if (OuterGrossWeight > MaxWeigh)
            {
                showMessage("请注意原发净重填写数量");
                return;
            }

            if (billModel.OuterWeightImg == null || billModel.OuterWeightImg == "")
            {
                showMessage("请上传原发磅单");
                return;
            }
            String ifstatement = App.getConfig().IfStatement;
            if (ifstatement.Equals("0"))
            {
                bool flag = click_statement();
                if (!flag)
                {
                    NavigationService.GetNavigationService(this).GoBack();
                    return;
                }
            }

            //mainWindow.Speak("签到成功");
            String url = "http://" + App.getConfig().HttpServerIp + ":" + App.getConfig().HttpServerPort + "/guns/sysFileInfo/upload2";
            JObject json = new JObject();
            json.Add("id", billModel.Id);
            json.Add("facId", billModel.driverMacCard);
            //json.Add("facId", billModel.DriverCard);
            //json.Add("outNetWeight", (double.Parse(billModel.OuterGrossWeight) - double.Parse(billModel.OuterSkinWeight)));
            //json.Add("outerGrossWeight", billModel.OuterGrossWeight);
            json.Add("outerNetWeight", billModel.OuterGrossWeight);
            json.Add("outerSkinWeight", billModel.OuterSkinWeight);
            json.Add("outerWeightImg", billModel.OuterWeightImg);
            json.Add("carNumber", billModel.CarNumber);
            //json.Add("trailerNumber", billModel.TrailerNumber);
            HttpPostWindow httpPostWindow1 = new HttpPostWindow();
            httpPostWindow1.Owner = mainWindow;
            httpPostWindow1.setParamObject(json);

            httpPostWindow1.setOperation(HttpPostWindow.OperationType.uploadMakeCardResult.ToString());
            bool result1 = (bool)httpPostWindow1.ShowDialog();
            if (!result1)
            {
                string message = httpPostWindow1.getMessage();
                if (null == message || "".Equals(message))
                {
                    message = "车辆报到失败,请联系工作人员处理";
                }
                string warning = httpPostWindow1.getWarning();
                if (null != warning && "" != warning)
                {
                    mainWindow.Speak(warning);
                    showMessage(warning);
                    Thread.Sleep(1000);
                }
                mainWindow.Speak(message);
                showMessage(message);
                //if (player != null && player.IsRunning)
                //{
                //    player.SignalToStop();
                //    player.WaitForStop();

                //}
                //CardDeviceUtil.ReceiveCard();
                if (inputWindow != null)
                {
                    inputWindow.Hide();
                }
                if (carInputWindow != null)
                {
                    carInputWindow.Hide();
                }

                Index index1 = new Index(mainWindow);

                NavigationService.GetNavigationService(this).Navigate(index1);
                return;
            }

            showMessage("车辆报到完成");
            //if (player != null && player.IsRunning)
            //{
            //    player.SignalToStop();
            //    player.WaitForStop();

            //}
            if (vce != null)
            {
                vce.Close();

            }
            if (inputWindow != null)
            {
                inputWindow.Hide();
            }
            if (carInputWindow != null)
            {
                carInputWindow.Hide();
            }
            Index index = new Index(mainWindow);

            NavigationService.GetNavigationService(this).Navigate(index);
        }
        private void doMakeCardIC()//采购IC卡报道
        {

            mainWindow.BreakSpeak();


            if (billModel.OuterGrossWeight == null || billModel.OuterGrossWeight == "")
            {
                showMessage("请按照原发磅单填写原发净重");
                return;
            }
            double OuterGrossWeight = double.Parse(billModel.OuterGrossWeight);
            double MaxWeigh = double.Parse(App.getConfig().MaxWeigh);

            if (OuterGrossWeight > MaxWeigh)
            {
                showMessage("请注意原发净重填写数量");
                return;
            }



            if (billModel.OuterWeightImg == null || billModel.OuterWeightImg == "")
            {
                showMessage("请上传原发磅单");
                return;
            }
            String ifstatement = App.getConfig().IfStatement;
            if (ifstatement.Equals("0"))
            {
                bool flag = click_statement();
                if (!flag)
                {
                    NavigationService.GetNavigationService(this).GoBack();
                    return;
                }
            }
            //--------------------IC卡-----------------------------------------

            MakeCardWindow makeCardWindow = new MakeCardWindow();
            makeCardWindow.setModel(billModel);
            makeCardWindow.Owner = mainWindow;
            bool result = (bool)makeCardWindow.ShowDialog();
            if (result)
            {
                // ReadCardWindow readCardWindow = new ReadCardWindow();
                //BillModel billModel1 = new BillModel();
                //readCardWindow.billModel = billModel1;
                //readCardWindow.Owner = mainWindow;
                //bool result1 = (bool)readCardWindow.ShowDialog();
                //if (result)
                //{
                JObject json1 = new JObject();
                json1.Add("guidCode", billModel.DriverCard);
                int checkResult = this.checkCard(json1);//json与ReadCardWindow的bill对比
                //--------------------IC卡-----------------------------------------
                //mainWindow.Speak("签到成功");
                String url = "http://" + App.getConfig().HttpServerIp + ":" + App.getConfig().HttpServerPort + "/guns/sysFileInfo/upload2";
                JObject json = new JObject();
                json.Add("id", billModel.Id);
                json.Add("facId", billModel.DriverCard);
                //json.Add("outNetWeight", (double.Parse(billModel.OuterGrossWeight) - double.Parse(billModel.OuterSkinWeight)));
                //json.Add("outerGrossWeight", billModel.OuterGrossWeight);
                json.Add("outerNetWeight", billModel.OuterGrossWeight);
                json.Add("outerSkinWeight", billModel.OuterSkinWeight);
                json.Add("outerWeightImg", billModel.OuterWeightImg);
                json.Add("carNumber", billModel.CarNumber);
                //json.Add("trailerNumber", billModel.TrailerNumber);
                HttpPostWindow httpPostWindow1 = new HttpPostWindow();
                httpPostWindow1.Owner = mainWindow;
                httpPostWindow1.setParamObject(json);

                httpPostWindow1.setOperation(HttpPostWindow.OperationType.uploadMakeCardResult.ToString());
                bool result1 = (bool)httpPostWindow1.ShowDialog();
                if (!result1)
                {
                    string message = httpPostWindow1.getMessage();
                    if (null == message || "".Equals(message))
                    {
                        message = "车辆报到失败,请联系工作人员处理";
                    }
                    string warning = httpPostWindow1.getWarning();
                    if (null != warning && "" != warning)
                    {
                        mainWindow.Speak(warning);
                        showMessage(warning);
                        Thread.Sleep(1000);
                    }
                    mainWindow.Speak(message);
                    showMessage(message);
                    CardDeviceUtil.ReceiveCard();//收回卡
                    if (inputWindow != null)
                    {
                        inputWindow.Hide();
                    }
                    if (carInputWindow != null)
                    {
                        carInputWindow.Hide();
                    }

                    Index index1 = new Index(mainWindow);

                    NavigationService.GetNavigationService(this).Navigate(index1);
                    return;
                }
                showMessage("车辆报到完成");
                MakeCardSucces();//报道完成弹出卡
                //if (player != null && player.IsRunning)
                //{
                //    player.SignalToStop();
                //    player.WaitForStop();

                //}
                if (vce != null)
                {
                    vce.Close();

                }
                if (inputWindow != null)
                {
                    inputWindow.Hide();
                }
                if (carInputWindow != null)
                {
                    carInputWindow.Hide();
                }
                Index index = new Index(mainWindow);

                NavigationService.GetNavigationService(this).Navigate(index);
            }
        }

        private int checkCard(JObject paramObj)
        {
            ReadCardWindow readcardWindow = new ReadCardWindow();

            bool result = (bool)readcardWindow.ShowDialog();
            if (!result)
            {
                return -1;
            }
            String guidCode = paramObj["guidCode"].ToString();
            if (!guidCode.Equals(readcardWindow.billModel.DriverCard))
            {
                return -2;
            }
            return 1;
        }

        private void MakeCardSucces()
        {
            showMessage("制卡成功,请取卡");
            CardDeviceUtil.PopupCard();
           // Reader.hc_exit(icdev);


        }
        private void MakeCardError()
        {
            showMessage("制卡失败,请联系管理员");
        }


        private void doInput(object sender, RoutedEventArgs e)
        {
            String val = ((Button)sender).Content.ToString();

            inputText(val);
        }
        private void inputText(String val)
        {
            String value = "";
            //if (curInputTag == "wp")
            //{
            //    value = this.wpText.Text;
            //}
            //else if (curInputTag == "wm")
            //{
            //    value = this.wmText.Text;
            //}
             
            if (curInputTag == "mobile")
            {
                value = this.mobileText.Text;
            }

            String value2 = "";
            if ("-1".Equals(val))
            {
                if (value.Length > 0)
                {
                    value2 = value.Substring(0, value.Length - 1);
                }
            }
            else
            {
                value2 = getNumField(value, val);
            }

            //if (curInputTag == "wp")
            //{
            //    this.wpText.Text = value2;
            //}
            //else if (curInputTag == "wm")
            //{
            //    this.wmText.Text = value2;
            //}
            //else
            if (curInputTag == "mobile")
            {
                this.mobileText.Text = value2;
            }
        }
        private String getNumField(String val, String inputVal)
        {
            if (inputVal == "消除")
            {
                return "";
            }
            if (inputVal == "." && curInputTag == "mobile")
            {
                return val;
            }
            if (inputVal == "." && "".Equals(val))
            {
                return val;
            }
            if (inputVal == "." && val.IndexOf(".") >= 0)
            {
                return val;
            }

            if (curInputTag == "mobile" && val.Length >= 11)
            {
                return val;
            }

            if ((curInputTag == "wp" || curInputTag == "wm") && val.IndexOf(".") >= 0)
            {
                if (val.IndexOf(".") + 3 == val.Length) return val;
            }
            if ((curInputTag == "wp" || curInputTag == "wm") && !"".Equals(val))
            {
                if (double.Parse(val + inputVal) > 99.99) return val;
            }

            String value = val;

            value = val + inputVal;

            return value;
        }

        public void MMPage_KeyDown(object sender, KeyEventArgs e)
        {
            string val = getKeyValue(e.Key);
            if ("back".Equals(val))
            {
                inputText("-1");
            }
            else if ("point".Equals(val))
            {
                inputText(".");
            }
            else
            {
                if (e.Key.ToString().StartsWith("D"))
                {
                    inputText(val);
                }
            }
            //MessageBox.Show(e.Key.ToString());
            e.Handled = true;
        }

        private string getKeyValue(Key key)
        {
            string KeyValue = "-1";

            switch (key)
            {
                case Key.D1:
                    KeyValue = "1";
                    break;
                case Key.D2:
                    KeyValue = "2";
                    break;
                case Key.D3:
                    KeyValue = "3";
                    break;
                case Key.D4:
                    KeyValue = "4";
                    break;
                case Key.D5:
                    KeyValue = "5";
                    break;
                case Key.D6:
                    KeyValue = "6";
                    break;
                case Key.D7:
                    KeyValue = "7";
                    break;
                case Key.D8:
                    KeyValue = "8";
                    break;
                case Key.D9:
                    KeyValue = "9";
                    break;
                case Key.D0:
                    KeyValue = "0";
                    break;
                case Key.OemPeriod:
                    KeyValue = "point";
                    break;
                case Key.Back:
                    KeyValue = "back";
                    break;
                case Key.Enter:
                    KeyValue = "enter";
                    break;
            }
            return KeyValue;
        }
        private bool click_statement()
        {
            StatementWindow statementWindow = new StatementWindow();
            statementWindow.setPersonImage(this.imageBrush);
            statementWindow.setBillModel(this.billModel);

            Grid layer = new Grid() { Background = new SolidColorBrush(System.Windows.Media.Color.FromArgb(200, 0, 0, 0)) };
            UIElement original = mainWindow.Content as UIElement;//MainWindows父窗体
            mainWindow.Content = null;
            //容器Grid
            Grid container = new Grid();
            container.Children.Add(original);//放入原来的内容
            container.Children.Add(layer);//在上面放一层蒙板
            //将装有原来内容和蒙板的容器赋给父级窗体
            mainWindow.Content = container;
            statementWindow.Owner = mainWindow;
            bool result = (bool)statementWindow.ShowDialog();
            return result;
        }

        public void UploadImage(string uploadUrl, string imgPath, long id, string fileparameter = "file")
        {
            try
            {
                HttpWebRequest request = WebRequest.Create(uploadUrl) as HttpWebRequest;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                request.ServicePoint.Expect100Continue = false;

                string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
                request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
                byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
                byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

                int pos = imgPath.LastIndexOf("/");
                string fileName = imgPath.Substring(pos + 1);

                //请求头部信息
                StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"" + fileparameter + "\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
                byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());

                FileStream fs = new FileStream(imgPath, FileMode.Open, FileAccess.Read);
                byte[] bArr = new byte[fs.Length];
                fs.Read(bArr, 0, bArr.Length);
                fs.Close();

                Stream postStream = request.GetRequestStream();
                postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                postStream.Write(bArr, 0, bArr.Length);
                postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
                postStream.Close();

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                Stream instream = response.GetResponseStream();
                StreamReader sr = new StreamReader(instream, Encoding.UTF8);
                string content = sr.ReadToEnd();
                JObject rspJson = JObject.Parse(content);
                string code = rspJson["code"].ToString();
                if (code.Equals("00000"))
                {
                    JObject data = (JObject)rspJson.GetValue("data");
                    String filaName = (String)data.GetValue("fileObjectName");
                    doUpdateScreenPicture(filaName, id);
                }
            }
            catch (Exception ex) { }

        }
        private void doUpdateScreenPicture(String imagePath, long id)
        {
            JObject paramObject = new JObject();
            paramObject.Add("imagePath", imagePath);
            paramObject.Add("id", id);

            try
            {
                String serverIp = App.getConfig().HttpServerIp;
                String serverPort = App.getConfig().HttpServerPort;
                String response = HttpPostHelper.doHttpPost("http://" + serverIp + ":" + serverPort + "/qd-s-factory/clientApi/updateBillCardPicture", paramObject.ToString());
                JObject rspJson = JObject.Parse(response);

            }
            catch (Exception ex) { }
        }




        private void Button_TakePhoto(object sender, RoutedEventArgs e)
        {
            TakeTicketImg();

        }

        public void TakeTicketImg()
        {
            //try
            //{
            //    if (player.IsRunning)
            //    {
            //        BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
            //                        player.GetCurrentVideoFrame().GetHbitmap(),
            //                        IntPtr.Zero,
            //                         Int32Rect.Empty,
            //                        BitmapSizeOptions.FromEmptyOptions());
            //        PngBitmapEncoder pE = new PngBitmapEncoder();
            //        pE.Frames.Add(BitmapFrame.Create(bitmapSource));
            //        //String baseImagePath = App.getConfig().ImageSavePath;
            //        //String path = baseImagePath + "/" ;
            //        //if (Directory.Exists(path) == false)
            //        //{
            //        //    Directory.CreateDirectory(path);
            //        //}
            //        string picName = GetImagePath() + "\\" + "ticket" + ".jpg";
            //        if (File.Exists(picName))
            //        {
            //            File.Delete(picName);
            //        }
            //        using (Stream stream = File.Create(picName))
            //        {
            //            pE.Save(stream);
            //        }
            //        //拍照完成后关摄像头并刷新同时关窗体

            //        showMessage("磅单拍照完成");
            //        cardImage.Source = bitmapSource;
            //        //InfoEntryViewModel.ImgPath = picName;
            //        uploadPic(picName);
            //    }
            //}
            //catch (Exception ex)
            //{
            //    System.Windows.MessageBox.Show("摄像头异常：" + ex.Message);
            //}

        }

        private string GetImagePath()
        {
            string personImgPath = System.IO.Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory)
                         + System.IO.Path.DirectorySeparatorChar.ToString() + "PersonImg";
            if (!Directory.Exists(personImgPath))
            {
                Directory.CreateDirectory(personImgPath);
            }

            return personImgPath;
        }

        private void uploadPic(string picPath)
        {
            String url = "http://" + App.getConfig().HttpServerIp + ":" + App.getConfig().HttpServerPort + "/guns/sysFileInfo/uploadFactory";
            UploadImage(url, picPath);

        }

        public void UploadImage(string uploadUrl, string imgPath, string fileparameter = "file")
        {
            try
            {
                var dic = new Dictionary<string, string>() {
                    {"para1",1.ToString() },
                    {"para2",2.ToString() },
                    {"para3",3.ToString() },
                };
                var postData = "secretFlag=N&fileBucket=outweighbridgeimg";//转换成：para1=1&para2=2&para3=3
                var postUrl = string.Format("{0}?{1}", uploadUrl, postData);//拼接url
                HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                request.ServicePoint.Expect100Continue = false;

                string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
                request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
                byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
                byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

                int pos = imgPath.LastIndexOf("/");
                string fileName = imgPath.Substring(pos + 1);

                //请求头部信息
                StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"" + fileparameter + "\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
                byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());

                FileStream fs = new FileStream(imgPath, FileMode.Open, FileAccess.Read);
                byte[] bArr = new byte[fs.Length];
                fs.Read(bArr, 0, bArr.Length);
                fs.Close();

                Stream postStream = request.GetRequestStream();
                postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                postStream.Write(bArr, 0, bArr.Length);
                postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
                postStream.Close();

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                Stream instream = response.GetResponseStream();
                StreamReader sr = new StreamReader(instream, Encoding.UTF8);
                string content = sr.ReadToEnd();
                JObject rspJson = JObject.Parse(content);
                string code = rspJson["code"].ToString();
                if (code.Equals("00000"))
                {
                    JObject data = (JObject)rspJson.GetValue("data");
                    String filaName = (String)data.GetValue("fileUrl");
                    // billModel.OuterWeightImg = "http://" + App.getConfig().HttpServerIp + ":" + App.getConfig().HttpServerPort + "/guns/sysFileInfo/previewByObjectName?fileBucket=images&fileObjectName=" + filaName;
                    billModel.OuterWeightImg =  filaName;
                }
            }
            catch (Exception ex) { }

        }
        private void TextBox_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            string index = (string)((System.Windows.Controls.TextBlock)sender).Tag;
            int v = int.Parse(index);

             _syncContext.Post(showInputWindow, v);
            
        }
        private void Grid_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (carInputWindow != null)
            {
                carInputWindow.Hide();
            }
            if (inputWindow != null)
            {
                inputWindow.Hide();
            }
        }
        private void showInputWindow(object obj)
        {
            int index = (int)obj;
            viewModel.index = index;
            if (index == 1 || index == 2 )
            {
                if (carInputWindow != null)
                {
                    carInputWindow.Hide();
                }

                if (inputWindow == null)
                {
                    inputWindow = new KeyBoardWindow(callbackAction);
                    inputWindow.Owner = mainWindow;
                    inputWindow.Width = mainWindow.Width;
                    inputWindow.Left = mainWindow.Left;
                    inputWindow.Top = SystemParameters.PrimaryScreenHeight - inputWindow.Height;
                }
                inputWindow.maxLength = 7;
                inputWindow.getFlag("2");

                if (index == 2)
                {
                    inputWindow.viewModel.carNoArray.Clear();
                    foreach (String v in viewModel.waiPiWeighArray)
                    {
                        if (v != "")
                        {
                            inputWindow.viewModel.carNoArray.Add(v);
                        }

                    }
                }else if (index == 1)
                {
                    inputWindow.viewModel.carNoArray.Clear();
                    foreach (String v in viewModel.waiMaoWeighArray)
                    {
                        if (v != "")
                        {
                            inputWindow.viewModel.carNoArray.Add(v);
                        }

                    }
                }
                inputWindow.showKeys(3);
                inputWindow.Show();
            }else if (index == 3)
            {
                if (inputWindow != null)
                {
                    inputWindow.Hide();
                }
                if (carInputWindow == null)
                {
                    carInputWindow = new InputWindow(callbackAction);
                    carInputWindow.Owner = mainWindow;
                    carInputWindow.Width = mainWindow.Width;
                    carInputWindow.Left = mainWindow.Left;
                    carInputWindow.Top = SystemParameters.PrimaryScreenHeight - carInputWindow.Height;
                }
                carInputWindow.maxLength = 7;
                carInputWindow.viewModel.carNoArray.Clear();
                foreach (String v in viewModel.carNoArray02)
                {
                    if (v != "")
                    {
                        carInputWindow.viewModel.carNoArray.Add(v);
                    }

                }
                if (carInputWindow.viewModel.carNoArray.Count == 0)
                {
                    carInputWindow.showKeys(1);
                }
                else
                {
                    carInputWindow.showKeys(2);
                }
                carInputWindow.Show();
            }
            else
            {
                if (inputWindow != null && inputWindow.IsActive)
                {
                    inputWindow.Hide();
                }
                if (carInputWindow != null && carInputWindow.IsActive)
                {
                    carInputWindow.Hide();
                }
            }
        }

        private void CallBackExcute(int index, string val)
        {       
            if (viewModel.index == 3)
            {
                viewModel.carNoArray02[index] = val;
                //BillModel.PiNumberList.Add(val);
                //BillModel.PiNumberList[index] = val;
                billModel.TrailerNumber = String.Join("", viewModel.carNoArray02);  
            }

            if (viewModel.index == 1)
            {
                viewModel.waiMaoWeighArray[index] = val;
                //BillModel.PiNumberList.Add(val);
                //BillModel.PiNumberList[index] = val;
                string inputStr = String.Join("", viewModel.waiMaoWeighArray);
                billModel.OuterGrossWeight = inputStr;

            }

            if (viewModel.index == 2)
            {
                viewModel.waiPiWeighArray[index] = val;
                //BillModel.PiNumberList.Add(val);
                //BillModel.PiNumberList[index] = val;
                string inputStr = String.Join("", viewModel.waiPiWeighArray);
                billModel.OuterSkinWeight = inputStr;

            }
        }

        private  void doTakePhoto(object sender, RoutedEventArgs e)//拍照
        {
            
            
            
            try
            {
                int PhotoHeight = int.Parse(App.getConfig().PhotoHeight);
                int PhotoWidth = int.Parse(App.getConfig().PhotoWidth);
                int ClearMultiples = int.Parse(App.getConfig().ClearMultiples);
                int PhotoQuality = int.Parse(App.getConfig().PhotoQuality);
                int targetWidth = (int)vce.ActualWidth * ClearMultiples;
                int targetHeight = (int)vce.ActualHeight * ClearMultiples;
                InfoWindow closeWindow = new InfoWindow("摄像头未打开，请重新报道");
                if (targetWidth > PhotoQuality || targetHeight > PhotoQuality)  // 设置最大限制，例如5000
                {
                    vce.Close();

                    closeWindow.Owner = mainWindow;
                    closeWindow.ShowDialog();

                    Index index = new Index(mainWindow);
                    mainWindow.BreakSpeak();
                    inputWindow?.Hide();//返回首页
                    carInputWindow?.Hide();
                    //CardDeviceUtil.ReceiveCard();
                    NavigationService.GetNavigationService(this).Navigate(index);
                    return;
                }

                //RenderTargetBitmap bmp = new RenderTargetBitmap((int)vce.ActualWidth, (int)vce.ActualHeight, PhotoHeight, PhotoWidth, PixelFormats.Default);
                RenderTargetBitmap bmp = new RenderTargetBitmap(targetWidth, targetHeight, PhotoHeight, PhotoWidth, PixelFormats.Default);
                // RenderTargetBitmap bmp = new RenderTargetBitmap(PhotoWidth, PhotoHeight, PhotoHeight, PhotoWidth, PixelFormats.Default);
      
                System.Windows.Size size = new System.Windows.Size((int)vce.ActualWidth * ClearMultiples, (int)vce.ActualHeight * ClearMultiples);

        

              
                //vce.Measure(vce.RenderSize);
                //vce.Arrange(new Rect(vce.RenderSize));
                vce.Measure(size);//所占空间大小
                vce.Arrange(new Rect(size));
                bmp.Render(vce);//将vce渲染到bmp中
                BitmapEncoder encoder = new JpegBitmapEncoder//JpegBitmapEncoder专门处理 JPEG 格式的图像压缩和保存
                {//JpegBitmapEncoder）将图像编码并保存到 FileStream 中
                    QualityLevel = 100// JPEG 编码的质量级别100质量最好
                };
                encoder.Frames.Add(BitmapFrame.Create(bmp));//BitmapFrame 代表一个图像帧，包含图像的像素数据。
                //encoder 对象代表了一个图像编码器，
                //创建图片存储路径，每个工程一个文件夹
                string directory = AppDomain.CurrentDomain.BaseDirectory + "Images";
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                //可能会多次拍摄，在图片后加上时间戳
                //string imgName = "img" + DateTime.Now.ToString("yyyyMMddHHmmssffff");
                imgTempPath = AppDomain.CurrentDomain.BaseDirectory + "Images\\cardPhoto.bmp";
                ////AppDomain.CurrentDomain.BaseDirectory获取根目录，拼接图片地址
                if (File.Exists(imgTempPath))
                {
                    File.Delete(imgTempPath);
                }
                // FileStream fstream = new FileStream(imgTempPath, FileMode.Create);


                using (FileStream fstream = new FileStream(imgTempPath, FileMode.Create))//将图片数据保存到文件流中保存到指定路径下
                {
                    encoder.Save(fstream);//负责将编码的图像数据写入文件流，从而将图像保存到本地指定的路径

                    // vce.Pause();
                }

                // encoder.Save(fstream);
                //fstream.Close();
                //vce.Pause();

                uploadPic(imgTempPath);//上传图片
              //  UploadPicAsync(imgTempPath);


                LoadImage(billModel.OuterWeightImg);//设置榜单图片路径
                InfoWindow infoWindow = new InfoWindow("拍照中");
                infoWindow.Owner = mainWindow;
                infoWindow.ShowDialog();
            }
            catch (Exception ex)
            {
                if (vce.ActualWidth == 0 || vce.ActualHeight == 0)
                {
                    MessageBox.Show("请勿重复按钮");
                    return;
                }
                else
                {
                    MessageBox.Show(ex.Message+"2");
                    return;
                }
            }
        }
        private async Task UploadPicAsync(string imagePath)
        {
            // 异步上传逻辑
            await Task.Run(() => uploadPic(imagePath));
        }
        private void LoadImage(string imagePath)//磅单展示
        {
            
            this.takeImage.Source = GetImage(imagePath);//设置图片路径

            
        }
        public static BitmapImage GetImage(string imagePath)
        {
            BitmapImage bitmap = new BitmapImage();
            string url = "http://" + App.getConfig().HttpServerIp + ":" + App.getConfig().HttpServerPort + "/guns" + imagePath;


            //if (File.Exists(imagePath))
            if (imagePath!= null && imagePath!="")
            {

                // 设置图像源
                bitmap.BeginInit();
                bitmap.UriSource = new Uri(url);
                bitmap.EndInit();

            
            }
            return bitmap;
        }

        private void returnn(object sender, RoutedEventArgs e)//返回
        {
            vce.Close();
    
            this.NavigationService.GoBack();
        }

    }
}
